package cn.luowb.checkchat.controller;

import cn.luowb.checkchat.common.context.UserContext;
import cn.luowb.checkchat.common.result.Result;
import cn.luowb.checkchat.common.web.Results;
import cn.luowb.checkchat.dto.resp.MediaUploadRespDTO;
import cn.luowb.checkchat.service.MediaService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.util.List;

@RestController
@RequestMapping("/media")
@RequiredArgsConstructor
@Slf4j
@Tag(name = "媒体资源", description = "媒体文件上传相关接口")
public class MediaController {

    private final MediaService mediaService;

    @Operation(summary = "上传媒体资源（支持多文件）")
    @PostMapping("/upload")
    public Result<List<MediaUploadRespDTO>> uploadMedia(
            @Parameter(description = "要上传的媒体文件（可多选）") @RequestParam("files") MultipartFile[] files,
            @Parameter(description = "文件类型") @RequestParam(value = "type", required = false) String type,
            @Parameter(description = "存储文件夹") @RequestParam(value = "folder", required = false) String folder) {

        // 检查用户是否登录
        Long userId = UserContext.getUserId();
        if (userId == null) {
            return new Result<List<MediaUploadRespDTO>>()
                    .setCode("401")
                    .setMessage("用户未登录");
        }

        log.debug("用户 {} 上传媒体文件: type={}, folder={}, fileCount={}", userId, type, folder, files.length);

        List<MediaUploadRespDTO> results = mediaService.uploadMultipleMedia(files, type, folder, userId);
        return Results.success(results);
    }

    @Operation(summary = "上传单个媒体资源")
    @PostMapping("/upload/single")
    public Result<MediaUploadRespDTO> uploadSingleMedia(
            @Parameter(description = "要上传的媒体文件") @RequestParam("file") MultipartFile file,
            @Parameter(description = "文件类型") @RequestParam(value = "type", required = false) String type,
            @Parameter(description = "存储文件夹") @RequestParam(value = "folder", required = false) String folder) {

        // 检查用户是否登录
        Long userId = UserContext.getUserId();
        if (userId == null) {
            return new Result<MediaUploadRespDTO>()
                    .setCode("401")
                    .setMessage("用户未登录");
        }

        log.debug("用户 {} 上传单个媒体文件: type={}, folder={}, filename={}", userId, type, folder, file.getOriginalFilename());

        MediaUploadRespDTO result = mediaService.uploadMedia(file, type, folder, userId);
        return Results.success(result);
    }
}